package com.bigknow.appstore.web.framework.util;


import java.io.*;
import java.util.Base64;

/**
 * 序列化工具类，当rpc的json出现无法序列化传输的类时，可以考虑采用此类来处理，
 * 用rpc传字符串。
 * 1.1版本：改为jdk1.8 base64工具类，添加将对象直接序列化为base64字符串的方法
 *
 * @author chaos  #2016-3-8 将版本替换为1.1
 * @version 1.1
 */
public class SerializeUtil {

    private static Base64.Encoder encoder = Base64.getEncoder();

    private static Base64.Decoder decoder = Base64.getDecoder();

    public static byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos);) {
            // 序列化
            oos.writeObject(object);
            return baos.toByteArray();
        } catch (Exception e) {
        }
        return null;
    }

    public static String serializeToString(Object object) {
        return encoder.encodeToString(serialize(object));
    }

    public static Object unserializeByString(String base64) throws IOException {
        return unserialize(decoder.decode(base64));
    }

    public static Object unserialize(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bais);) {
            return ois.readObject();
        } catch (Exception e) {
        }
        return null;
    }
}
